package com.linkage.jz.bankruptcy.activity.Main;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.AddressInfo;
import com.linkage.jz.bankruptcy.bean.JsonBean;
import com.linkage.jz.bankruptcy.bean.MyAddr;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.GetJsonDataUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * @author AFAP
 * 创建地址
 */
public class CreateAddrActivity extends BaseActivity implements OnClickListener {
    private static final String TAG = CreateAddrActivity.class.getSimpleName();
    public final static String FROM_FLOW = "FROM_FLOW"; // 来自节点新建
    public final static String FROM_MEMBER = "FROM_MEMBER"; // 来自用户修改地址

    private String mFrom = "";

    public final static String KEY_FROM = "KEY_FROM";
    public final static String KEY_BEAN = "KEY_BEAN";

    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private MyAddr mAddress;

    private int provinceIndex = -1, cityIndex = -1, regionIndex = -1;
    private String province = "";
    private String city = "";
    private String region = "";

    private void initJsonData() throws Exception {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String cityName = jsonBean.get(i).getCityList().get(c).getName();
                cityList.add(cityName);//添加城市
                ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    city_AreaList.add("");
                } else {
                    city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                city_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                province_AreaList.add(city_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }
    }


    public ArrayList<JsonBean> parseData(String result) throws Exception {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        JSONArray data = new JSONArray(result);
        Gson gson = new Gson();
        for (int i = 0; i < data.length(); i++) {
            JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
            detail.add(entity);
        }
        return detail;
    }

    private EditText et_address, et_post;
    private TextView tv_ssq;
    private CheckBox ck_default;

    boolean isLoaded = false;

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {

    }

    @Override
    public void initView() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_create_my_addr);
        super.onCreate(savedInstanceState);
        mAddress = (MyAddr) getIntent().getSerializableExtra("item");
        if (mAddress != null) {
            titlebar_title.setText("修改地址");
        } else {
            titlebar_title.setText("新增地址");
        }
        mFrom = getIntent().getStringExtra(KEY_FROM);
        if (TextUtils.equals(mFrom, FROM_FLOW) || TextUtils.equals(mFrom, FROM_MEMBER)) {
            findViewById(R.id.area_post).setVisibility(View.VISIBLE);
            findViewById(R.id.area_default).setVisibility(View.GONE);
        }

        if(TextUtils.equals(mFrom, FROM_FLOW)){
            titlebar_title.setText("填写地址");
            mAddress = (MyAddr) getIntent().getSerializableExtra(KEY_BEAN);
        }



        initviews();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_ssq:
                if (isLoaded) {
                    InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    }
                    showPickerView();
                }
                break;

            case R.id.titlebar_menu_text:
                if (TextUtils.equals(getIntent().getStringExtra(KEY_FROM), FROM_MEMBER)) {
                    AddressInfo addressInfo = new AddressInfo();
                    addressInfo.setProvince(province);
                    addressInfo.setCity(city);
                    addressInfo.setRegion(region);
                    addressInfo.setAddress(et_address.getText().toString());
                    Intent intent = new Intent();
                    intent.putExtra("address", addressInfo);
                    setResult(RESULT_OK, intent);
                    finish();
                } else
                    saveData();
                break;
        }
    }

    OptionsPickerView pvOptions;

    private void showPickerView() {
        if (pvOptions == null) {
            pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    //返回的分别是三个级别的选中位置
                    String opt1tx = options1Items.size() > 0 ?
                            options1Items.get(options1).getPickerViewText() : "";

                    String opt2tx = options2Items.size() > 0
                            && options2Items.get(options1).size() > 0 ?
                            options2Items.get(options1).get(options2) : "";

                    String opt3tx = options2Items.size() > 0
                            && options3Items.get(options1).size() > 0
                            && options3Items.get(options1).get(options2).size() > 0 ?
                            options3Items.get(options1).get(options2).get(options3) : "";
                    String tx = opt1tx + " " + opt2tx + " " + opt3tx;

                    tv_ssq.setText(tx);
                    getCode(opt2tx + opt3tx);
                    province = opt1tx;
                    city = opt2tx;
                    region = opt3tx;

                    provinceIndex = options1;
                    cityIndex = options2;
                    regionIndex = options3;

                }
            })
                    .setTitleText("城市选择")
                    .setDividerColor(Color.BLACK)
                    .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                    .setContentTextSize(20)
                    .build();
            pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        }
        pvOptions.show();
        if (provinceIndex != -1 && cityIndex != -1 && regionIndex != -1) {
            pvOptions.setSelectOptions(provinceIndex, cityIndex, regionIndex);
        }
    }


    //初始化视图
    private void initviews() {
        titlebar_menu_text.setVisibility(View.VISIBLE);
        titlebar_menu_text.setOnClickListener(this);

        tv_ssq = findViewById(R.id.tv_ssq);
        et_address = findViewById(R.id.et_address);
        et_post = findViewById(R.id.et_post);
        ck_default = findViewById(R.id.ck_default);

        if (mAddress != null) {
            province = mAddress.province;
            city = mAddress.city;
            region = mAddress.region;
            String tx = province + " " + city + " " + region;
//                Toast.makeText(CreateAddrActivity.this, tx, Toast.LENGTH_SHORT).show();

            tv_ssq.setText(tx);
            et_address.setText(mAddress.address);
            et_post.setText(mAddress.zipCode);
            ck_default.setChecked(mAddress.defaut);
            provinceIndex = mAddress.provinceIndex;
            cityIndex = mAddress.cityIndex;
            regionIndex = mAddress.regionIndex;
        }

        new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... voids) {
                try {
                    initJsonData();
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }

                return true;
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                super.onPostExecute(aBoolean);
                isLoaded = aBoolean;
            }
        }.execute();

    }


    public void saveData() {
        String str_subject = tv_ssq.getText().toString();
        if (TextUtils.isEmpty(str_subject)) {
            ToastUtil.showShort("区域名称不能为空");
            return;
        }


        mShapeLoadingDialog.setLoadingText("提交信息中...");
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();


        Observable<JsonObject> observable = null;
        if (mAddress != null && !TextUtils.equals(mFrom, FROM_FLOW) ) {
            observable = Network
                    .getAPIService()
                    .updateAddress(getUserToken(), mAddress.id, province, city, region, et_address.getText().toString(), et_post.getText().toString(), ck_default.isChecked());
        } else {
            observable = Network
                    .getAPIService()
                    .saveAddress(getUserToken(), province, city, region, et_address.getText().toString(), et_post.getText().toString(), ck_default.isChecked());
        }

        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");
                        MyAddr bean = MyAddr.parse(data.getAsJsonObject("addressInfo"));
                        bean.setCityIndex(cityIndex);
                        bean.setProvinceIndex(provinceIndex);
                        bean.setRegionIndex(regionIndex);

                        Intent intent = new Intent();
                        intent.putExtra("id", bean.getId());
                        intent.putExtra("desc", bean.getFullAddress());
                        intent.putExtra("bean",bean);
                        setResult(RESULT_OK, intent);

                        ToastUtil.showShort("提交成功");
                        finish();
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }


    public void getCode(String city) {


        OkHttpClient okHttpClient = new OkHttpClient();
        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();


        RequestBody requestBody = new FormBody.Builder()
                .add("appid", Consts.appid)

                .build();

        String url = "http://cpdc.chinapost.com.cn/web/index.php?m=postsearch&c=index&a=ajax_addr&searchkey=";
        url = url + city;

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();


                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    if (object.optInt("errcode") == 0) {

                        JSONArray ary = object.optJSONArray("rs");
                        for (int i = 0; i < ary.length(); i++) {
                            JSONObject obj = (JSONObject) ary.get(i);
                            String code = obj.optString("POSTCODE");
                            if (!"".equalsIgnoreCase(code) && !"-1".equalsIgnoreCase(code)) {
                                et_post.setText(code);

                            }
                        }
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
//                                finish();

                            }

                        });
                    } else {
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI


                            }

                        });
                    }

                    str = "";
                } catch (Exception ex) {

                    ex.printStackTrace();
                }
            }
        });


    }

}

